<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      http-equiv="X-UA-Compatible"
      content="IE=edge"
    />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0"
    />
    <title>多个缓冲区和数据偏移</title>
    <script src="../libs/index.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      canvas {
        margin: 50px auto 0;
        display: block;
        background-color: #fff;
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas
      width="400"
      height="400"
      id="canvas"
    >
      此浏览器不支持canvas
    </canvas>

    <script>
      /** @type {HTMLCanvasElement} */
      const ctx = document.getElementById('canvas')
      const gl = ctx.getContext('webgl')

      const VERTEX_SHADER_SOURCE = `
        // 定义变量 只传递顶点数据 只能在顶点着色器使用
        attribute vec4 aPosition;
        attribute float aPointSize;
        // 必须要存在的main函数
        void main() {
          // 点的位置
          gl_Position = aPosition;
          // 点的大小
          gl_PointSize = aPointSize;
        }
      `
      // 片元着色器
      const FRAGMENT_SHADER_SOURCE = `
        void main() {
          // 点的颜色
          gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
      `
      const program = initShader(
        gl,
        VERTEX_SHADER_SOURCE,
        FRAGMENT_SHADER_SOURCE
      )

      const aPosition = gl.getAttribLocation(program, 'aPosition')
      const aPointSize = gl.getAttribLocation(program, 'aPointSize')

      const points = new Float32Array([-0.5, -0.5, 0.5, -0.5, 0.0, 0.5])
      const size = new Float32Array([10, 20, 30])

      // 创建缓存区
      const bufferPosition = gl.createBuffer()
      gl.bindBuffer(gl.ARRAY_BUFFER, bufferPosition)
      gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW)
      gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
      // 激活aPosition
      gl.enableVertexAttribArray(aPosition)

      // 在创建一个缓存区
      const bufferSize = gl.createBuffer()
      gl.bindBuffer(gl.ARRAY_BUFFER, bufferSize)
      gl.bufferData(gl.ARRAY_BUFFER, size, gl.STATIC_DRAW)
      gl.vertexAttribPointer(aPointSize, 1, gl.FLOAT, false, 0, 0)
      gl.enableVertexAttribArray(aPointSize)

      gl.drawArrays(gl.POINTS, 0, 3)
    </script>
  </body>
</html>
